import {
    Controller, Get, Post, Put, Delete, Body, Param,
    Query, BadRequestException, UseGuards, UploadedFile,
    UploadedFiles, UseInterceptors
} from '@nestjs/common';
import { Types } from 'mongoose';
import { WorkflowTemplateService } from './workflow-template.service';
import { CreateWorkflowTemplateDto } from './dto/create-workflow-template.dto';
import { ApiTags, ApiOperation, ApiResponse, ApiConsumes, ApiBody } from '@nestjs/swagger';
import { FileInterceptor, FilesInterceptor } from '@nestjs/platform-express';
import { FileUploadService } from '../common/services/file-upload.service';

@ApiTags('templates')
@Controller('templates')
export class WorkflowTemplateController {
    constructor(
        private readonly workflowTemplateService: WorkflowTemplateService,
        private readonly fileUploadService: FileUploadService,
    ) { }

    @Post('upload/thumbnail')
    @ApiOperation({ summary: '上传模板缩略图' })
    @ApiConsumes('multipart/form-data')
    @UseInterceptors(FileInterceptor('file'))
    async uploadThumbnail(@UploadedFile() file: Express.Multer.File) {
        return this.fileUploadService.uploadFile(file, 'thumbnails');
    }

    @Post('upload/previews')
    @ApiOperation({ summary: '上传模板预览图' })
    @ApiConsumes('multipart/form-data')
    @UseInterceptors(FilesInterceptor('files', 5))
    async uploadPreviews(@UploadedFiles() files: Express.Multer.File[]) {
        return this.fileUploadService.uploadMultipleFiles(files, 'previews');
    }

    @Post()
    @ApiOperation({ summary: '创建新模板' })
    async create(@Body() createDto: CreateWorkflowTemplateDto) {
        try {
            return await this.workflowTemplateService.create(createDto);
        } catch (error) {
            if (error.name === 'ValidationError') {
                throw new BadRequestException(error.message);
            }
            throw error;
        }
    }

    @Get()
    @ApiOperation({ summary: '获取模板列表' })
    async findAll(
        @Query('category') category?: string,
        @Query('search') search?: string,
        @Query('page') page?: number,
        @Query('pageSize') pageSize?: number,
        @Query('sort') sort?: string,
    ) {
        console.log('Fetching templates with params:', { category, search, page, pageSize, sort });
        return this.workflowTemplateService.findAll({
            category,
            search,
            page,
            limit: pageSize,
            sort
        });
    }

    @Get('categories')
    @ApiOperation({ summary: '获取所有分类' })
    async getCategories() {
        console.log('Fetching categories...');
        return this.workflowTemplateService.getCategories();
    }

    @Get(':id')
    @ApiOperation({ summary: '获取单个模板详情' })
    async findOne(@Param('id') id: string) {
        if (!Types.ObjectId.isValid(id)) {
            throw new BadRequestException('Invalid ID format');
        }
        return this.workflowTemplateService.findOne(id);
    }

    @Put(':id')
    @ApiOperation({ summary: '更新模板' })
    async update(
        @Param('id') id: string,
        @Body() updateDto: Partial<CreateWorkflowTemplateDto>
    ) {
        return this.workflowTemplateService.update(id, updateDto);
    }

    @Delete(':id')
    @ApiOperation({ summary: '删除模板' })
    async remove(@Param('id') id: string) {
        return this.workflowTemplateService.remove(id);
    }

    @Post(':id/views')
    @ApiOperation({ summary: '增加查看次数' })
    async incrementViews(@Param('id') id: string) {
        return this.workflowTemplateService.incrementViews(id);
    }

    @Post(':id/likes')
    @ApiOperation({ summary: '点赞' })
    async toggleLike(@Param('id') id: string) {
        return this.workflowTemplateService.toggleLike(id);
    }
} 